package com.jiuzhi;

import com.jiuzhi.web.MyBasicErrorController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.Servlet;
import java.util.List;

/**
 * 全局异常处理，不用springboot默认的basicErrorController 自定义异常处理；
 * spring mvc配置 放于此处，例如拦截器等；
 * Created by moloch on 2017/8/31.
 */
@Configuration
//@EnableWebMvc//，加上此行，则spring boot的默认mvc配置失效，需要自己配置所有
@ConditionalOnWebApplication
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@AutoConfigureBefore(WebMvcAutoConfiguration.class)
@EnableConfigurationProperties(ResourceProperties.class)
public class WebApplicationConfig extends WebMvcConfigurerAdapter {

    @Autowired(required = false)
    private List<ErrorViewResolver> errorViewResolvers;
    private final ServerProperties serverProperties;

    public WebApplicationConfig(
            ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Bean
    public MyBasicErrorController myBasicErrorController(ErrorAttributes errorAttributes) {
        return new MyBasicErrorController(errorAttributes, this.serverProperties.getError(),
                this.errorViewResolvers);
    }

    @Override
    public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) {
        super.addReturnValueHandlers(returnValueHandlers);
    }
}
